package com.xiguthings.xiniu.iot.post.poster;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.xiguthings.xiniu.iot.common.PostData;

@Component
public class SendPostThreadPool {
    private final Logger LOGGER = LoggerFactory.getLogger(SendPostThreadPool.class);
    @Autowired
    private PostCenter postCenter;
    @Value("${post.pool.size}")
    private int threadCount;
    private ExecutorService threadPool;

    /**
     * 初始化
     */
    @PostConstruct
    void init() {
        threadPool = Executors.newFixedThreadPool(threadCount);
    }

    /**
     * 程序关闭,关闭线程池
     */
    @PreDestroy
    void fin() {
        shutdown();
    }

    public void shutdown() {
        if (threadPool != null) threadPool.shutdown();
        try {
            if (!threadPool.awaitTermination(5000, TimeUnit.MILLISECONDS)) {
                LOGGER.info("Timed out waiting for consumer threads to shut down, exiting uncleanly");
            }
        } catch (InterruptedException e) {
            LOGGER.info("Interrupted during shutdown, exiting uncleanly");
        }
    }

    /**
     * 执行发送单条post
     *
     * @param data
     * @return
     */
    public void executeSendPost(PostData data) {
        Runnable runnable = new SendPostRunable(data,postCenter);
        threadPool.execute(runnable);
    }
    
   

    
    
}
